﻿using Albatross.WPF.Common.ViewModels;
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Albatross.SharePoint.Explorer.ViewModels {
	public class FieldViewModel : ClientObjectViewModel{
		public FieldViewModel(ClientContext context, string name, Field field) : base(context, name, field) { }

		Field Field { get { return (Field)ClientObject; } }
		public override string GetTreeItemTitle() {
			if (Name == string.Empty) {
				return string.Format("{0} ({1})", Field.Title, Field.InternalName);
			} else {
				return Name;
			}
		}

		
		public const string JSLinkPropertyName = "JSLink";
		private string _jsLink;
		public string JSLink {
			get { return _jsLink; }
			set {
				if (_jsLink == value) { return; }
				RaisePropertyChanging(JSLinkPropertyName);
				_jsLink = value;
				RaisePropertyChanged(JSLinkPropertyName);
			}
		}

		public override IEnumerable<string> PreloadProperties {
			get {
				return new string[] { "SchemaXml", "JSLink" };
			}
		}

		public override string GetContentTitle() {
			return string.Format("{0} ({1})", Field.Title, Field.InternalName );
		}
		protected override Tuple<IEnumerable<ObjectProperty>, IEnumerable<ClientObjectViewModel>> Load() {
			Tuple<IEnumerable<ObjectProperty>, IEnumerable<ClientObjectViewModel>> data = base.Load();
			string url = Context.Url + @"/_layouts/15/" + Field.JSLink;
			WebRequest webRequest = HttpWebRequest.Create(url);
			webRequest.UseDefaultCredentials = true;
			using (WebResponse response = webRequest.GetResponse()) {
				using (Stream stream = response.GetResponseStream()) {
					JSLink = new StreamReader(stream).ReadToEnd();
				}
			}
			return data;
		}
	}
}
